<template>
	<div class="system-role">
        <div class="top">
			<Row :gutter="10">
				<Col :span="4">
					<Input v-model="keyWord" placeholder="输入会员卡号/姓名/手机号码" />
				</Col>
				<Col :span="4">
					<Select placeholder="请选择患者类型" v-model="customerType">
						<Option v-for="item in diseaseTypeList" :value="item.id" :key="item.value">{{ item.itemValue }}</Option>
					</Select>
				</Col>
				<Col :span="4">
					<Select v-model="tagList" placeholder="请选择患者标签">
						<Option v-for="item in totalTagList" :value="item.id" :key="item.id">{{ item.tagName }}</Option>
					</Select>
				</Col>
                <Col :span="4">
					<DatePicker style="width: 100%" type="daterange" v-model="daterange" placement="top-start" placeholder="请选择随访时间范围"></DatePicker>
				</Col>
				<Col :span="4">
					<Button type="primary" @click="search">查询</Button>
					<Button type="default" plain @click="reset">清空</Button>
				</Col>
				<Col :span="4" type="flex" align="right">
					<Button type="primary" @click="updateBatch">批量计划</Button>
				</Col>
			</Row>
		</div>

        <!-- <div class="top">
			<Row :gutter="10" justify="center">
				<Col span="4">
					<Button type="success" icon="md-add" @click="updateBatch">批量随访</Button>
				</Col>
			</Row>
		</div> -->

		<Drawer :title="isBatch?'批量随访':'健康随访'" v-model="showDrawer" :width="720" :mask-closable="false">
			<Form :model="editedItem" :rules="rules">
                <div v-if="isBatch===false">基本信息</div>
                <Row :gutter="10" v-if="isBatch===false">
                    <Col :span="12">
                        <label class="label" for>姓名:</label>
                        <span>{{editedItem.customerName}}</span>
                    </Col>
                    
                    <Col :span="12">
                        <label class="label" for>出生年月:</label>
                        <span>{{editedItem.birthday}}</span>
                    </Col>
                    <Col :span="12">
                        <label class="label" for>性别:</label>
                        <span v-if="String(editedItem.sex)==='1'">男</span>
                        <span v-else-if="String(editedItem.sex)==='2'">男</span>
                        <span v-else>-</span>
                    </Col>
                    <Col :span="12">
                        <label class="label" for>手机号码:</label>
                        <span>{{editedItem.mobile}}</span>
                    </Col>
                    <Col :span="12">
                        <label class="label" for>身份证号:</label>
                        <span>{{editedItem.customerInfo.idCard}}</span>
                    </Col>
                    <Col :span="12">
                        <label class="label" for>档案编号:</label>
                        <span>{{editedItem.customerFileNumber}}</span>
                    </Col>
                    
                    <Col :span="12">
                        <label class="label" for>身高(cm):</label>
                        <span>{{editedItem.customerInfo.height}}</span>
                    </Col>
                    <Col :span="12">
                        <label class="label" for>体重(kg):</label>
                        <span>{{editedItem.customerInfo.weight}}</span>
                    </Col>
                    <Col :span="12">
                        <label class="label" for>BMI指数:</label>
                        <span>-</span>
                    </Col>
                    <Col :span="12">
                        <label class="label" for>患者类型:</label>
                        <span>{{editedItem.customerInfo.diseaseType}}</span>
                    </Col>
                    <Col :span="12">
                        <label class="label" for>确诊时间:</label>
                        <span>{{editedItem.customerInfo.careTime}}</span>
                    </Col>
                    <Col :span="12">
                        <label class="label" for>并发症:</label>
                        <span>{{editedItem.customerInfo.complication}}</span>
                    </Col>
                </Row>

                <Row :gutter="10" v-if="isBatch">
                    <FormItem label="随访患者:" label-position="left">
                        <Select multiple v-model="selection" placeholder="请选择一名或多名患者">
                            <Option
                                class="select"
                                v-for="item in items"
                                :value="item.id"
                                :key="item.id"
                            >{{ item.customerName }}</Option>
                        </Select>
                    </FormItem>
                </Row>
                <Divider v-if="isBatch===false" />
                <div  v-if="isBatch===false">计划信息</div>
                <Row type="flex" :gutter="10">
                    <Col :span="12">
                        <FormItem label="计划人员:" label-position="left">
                            <Select v-model="editedItem.planUserId" class="cube" placeholder="请选择计划人员">
								<Option
									class="select"
									v-for="item in userList"
									:value="item.id"
									:key="item.id"
								>{{ item.username }}</Option>
							</Select>
                        </FormItem>
					</Col>
                    
                    <Col :span="12">
                        <FormItem label="随访模板:" label-position="left">
                            
                            <Select v-model="editedItem.templateId" class="cube" placeholder="请选择随访模板">
								<Option
									class="select"
									v-for="item in templateFollowList"
									:value="item.id"
									:key="item.id"
								>{{ item.templateName }}</Option>
							</Select>
                        </FormItem>
					</Col>
                    <Col :span="12">
                        <FormItem label="随访类型:" label-position="left">
                            <Select v-model="editedItem.followType" class="cube" placeholder="请选择随访类型">
								<Option
									class="select"
									v-for="item in typeFollowList"
									:value="item.id"
									:key="item.id"
								>{{ item.itemValue }}</Option>
							</Select>
                        </FormItem>
					</Col>
                    <Col :span="12" >
                        <FormItem label="计划时间:" label-position="left">
                            <DatePicker class="time-picker" v-model="editedItem.planTime" type="datetime" placeholder="请选择计划时间" />
						</FormItem>
					</Col>
                    <Col :span="24">
						<FormItem label="随访内容:" label-position="left" prop="followContent">
							<Input  class="cube" type="textarea" v-model="editedItem.followContent" placeholder="" />
						</FormItem>
					</Col>
				</Row>
			</Form>
			<div class="demo-drawer-footer">
				<Button style="margin-right: 8px" @click="close">取消</Button>
				<Button type="primary" @click="save" :loading="editedIndex===-1?createLoading:updateLoading">保存</Button>
			</div>
		</Drawer>
		<div>
			<div>
				<Table
					:loading="loading"
					highlight-row
					ref="currentRowTable"
					:columns="tableColumns"
					:data="items"
                    @on-selection-change="tableSelectionchange"
				>

                

                    <template slot-scope="{ row }" slot="birthday">
                        <span>{{row.birthday | AGE}}</span>
                    </template>


                    <template slot-scope="{ row }" slot="addTime">
                        <span>{{row.addTime | YMDHMS}}</span>
                    </template>
                    <template slot-scope="{ row }" slot="customerType">
                        <span>{{getCustomerType(row)}}</span>
                    </template>
					<template slot-scope="{ row }" slot="sex">
                        <span v-if="Number(row.sex)===1">男</span>
                        <span v-else-if="Number(row.sex)===2">女</span>
                        <span v-else>-</span>
                    </template>
					<template slot-scope="{row}" slot="action">
                        <!-- /customer/detail?id=19 -->
                        <Button class="plain-btn" type="text" :to="{path: '/customer/detail',query:{id:row.id}}">档案</Button>
				        <Button class="plain-btn" type="text" @click="create(row)">制定计划</Button>
						<!-- <Button type="primary" size="small" @click="update(row)">修改</Button> -->
						<!-- <Button class="ml10" type="primary" ghost size="small" @click="remove(row)">删除</Button> -->
					</template>
				</Table>
                <Row class="pagination">
                    <Col align="right">
                        <Page :current="page" :total="totalNum" show-total @on-change="pageChange" />
                    </Col>
                </Row>
			</div>
		</div>
	</div>
</template>
<script>
import { customerPageQueryList ,customerGet} from '@api/customer.js'
import { followAdd, followBatchAdd, } from '@api/follow.js'
import { typeFollowQueryList } from '@api/typeFollow.js'
import { templateFollowPageQueryList } from '@api/followTemplate.js'
import { dicGetItemByCode } from '@api/dic.js'
import { tagPageQueryList } from '@api/tag.js'
import { userPageQueryList } from '@api/user.js'
import moment from 'moment'
export default {
	data() {
		return {
            rules: {
				interventionContent: [{ required: true, message: '请输入随访内容', trigger: 'blur' }, { type: 'string', min: 6, message: '最少6个字符', trigger: ['blur','change'] }]
            },
			showDrawer: false,
			loading: false,
			updateLoading: false,
            createLoading: false,
            editedIndex: -1,
            
			editedItem: {
                templateId: '',
                followType: '',
                customerId: '',
                followContent: '',
                planTime: '',
                planUserId: '',

                customerName: '',
                mobile: '',
                sex: '',
                birthday: '',
                headimgurl: '',
                customerFileNumber:'',
                customerInfo: {
                    idCard: '',
                    contactPerson: '',
                    contactPhone: '',
                    height: '',
                    weight: '',
                    marryFlag:'0',//是否已婚，0：不是，1：是
                    profession: '',
                    diseaseType: '',
                    complication:'',
                    careTime: '',
                    vipNumber: '',
                    province: '',
                    provinceId: '',
                    city: '',
                    cityId: '',
                    district:'',
                    districtId: '',
                    address: '',
                    remark: '', //必须
                },
                customerHistory: { //健康信息
                    diseaseHistory: '',
                    nowHistory:'',
                    allergyHistory: '',
                    familyHistory: '',
                    nowTreatment: '',
                    passTreatment: '',
                },
                customerHabit: {
                    labor: '',
                    smoke: '',
                    smokeRate: '',
                    drink: '',
                    drinkRate: '',
                    exercise: '',
                },
                customerFamilyList: [],
			},
			defaultItem: {
                templateId: '',
                followType: '',
                customerId: '',
                followContent: '',
                planTime: '',
                planUserId: '',

				customerName: '',
                mobile: '',
                sex: '', 
                birthday: '',
                headimgurl: '',
                customerFileNumber: '',
                customerInfo: {
                    idCard: '',
                    contactPerson: '',
                    contactPhone: '',
                    height: '',
                    weight: '',
                    marryFlag:'0',//是否已婚，0：不是，1：是
                    profession: '',
                    diseaseType: '',
                    complication:'',
                    careTime: '',
                    vipNumber: '',
                    province: '',
                    provinceId: '',
                    city: '',
                    cityId: '',
                    district:'',
                    districtId: '',
                    address: '',
                    remark: '', //必须
                },
                customerHistory: { //健康信息
                    diseaseHistory: '',
                    nowHistory:'',
                    allergyHistory: '',
                    familyHistory: '',
                    nowTreatment: '',
                    passTreatment: '',
                },
                customerHabit: {
                    labor: '',
                    smoke: '',
                    smokeRate: '',
                    drink: '',
                    drinkRate: '',
                    exercise: '',
                },
                customerFamilyList: [],
            },
            showTimePicker: false,
			items: [],
			page: 1,
			pageSize: 10,
			totalNum: 0,
			tableColumns: [
                {
					width: 60,
                    type: 'selection',
                },
                {
					title: '档案编号',
					align: 'left',
					key: 'customerFileNumber',
				},
				{
					title: '姓名',
					align: 'left',
					key: 'customerName',
                },
              
				{
					title: '性别',
					align: 'left',
					slot: 'sex',
				},
				{
					title: '年龄',
					align: 'left',
					slot: 'birthday',
					width: 100
				},
				{
					title: '患者类型',
					align: 'left',
					slot: 'customerType',
					width: 100,
				},
				{
					title: '患者标签',
					align: 'left',
					key: 'tags',
					width: 250
				},
				{
					title: '手机号码',
					align: 'left',
					key: 'mobile',
					width: 120
				},
				{
					title: '最近随访时间',
					slot: 'addTime',
					align: 'left',
					width: 170
				},
				{
					title: '操作',
					slot: 'action',
					align: 'left',
					width: 200,
					align: 'left',
				}
            ],

            daterange: ["",""],
            customerType: "",
            keyWord: "",
            
            selection: [],
            isBatch: false,
            typeFollowList: [],
            templateFollowList: [],
            diseaseTypeList: [],
            tagList: [],
            userList: [],
            totalTagList: [],
		}
	},
	mounted() {
        this.customerPageQueryList();
        this.typeFollowQueryList();
        this.templateFollowPageQueryList();
        this.getDiseaseTypeList();
        this.tagPageQueryList();
        this.userPageQueryList();
	},
	computed: {
		alertTitle() {
			return this.editedIndex === -1 ? '新增' : '修改'
        },
	},
	methods: {
        userPageQueryList() {
			userPageQueryList({
				page:1,
				pageSize:1000,
			}).then(res => this.userList = res.data.items)
		},
        tagPageQueryList() {
            tagPageQueryList({page:1,pageSize:1000}).then(res => {
                if (res.code === '0') {
                    this.totalTagList = res.data.items
                } else {
                    this.$Modal.warning({
                        title: '查询患者标签',
                        content: res.errMsg || '查询错误'
                    })
                }
            })
        },
        getCustomerType(row) {
            const { customerType } = row;
            const { diseaseTypeList } = this;
            const idx = diseaseTypeList.findIndex((item,i) => String(item.id) === customerType)
            if (idx > -1) {
                return diseaseTypeList[idx]['itemValue']
            } else {
                return '-'
            }
        },
        search() {
            this.page = 1;
            this.pageSize = 10;
            this.customerPageQueryList()
        },
        reset() {
            this.page = 1;
            this.pageSize = 10;
            this.customerType= '';
            this.keyWord='';
            this.tagList= [];
            this.daterange= [];
        },
        async getDiseaseTypeList() {
            console.log('getDiseaseTypeList>')
            const res = await dicGetItemByCode({
                typeCode:'disease_type'
            })
            this.diseaseTypeList = res.data;
        },
        templateFollowPageQueryList(){
            templateFollowPageQueryList({page: 1,pageSize: 1000}).then(res => {
                if (res.code === '0') {
                    this.templateFollowList = res.data.items
                    console.log('templateFollowList-->', this.templateFollowList)
                } else {
                    this.modal(res,'查询随访模板')
                }
            })
        },
        typeFollowQueryList(){
            typeFollowQueryList().then(res => {
                if (res.code === '0') {
                    this.typeFollowList = res.data

                } else {
                    this.modal(res,'查询随访类型')
                }
            })
        },
        
        radioChange() {
            console.log("radioChange")
        },
        tableSelectionchange(selection){
            selection.map((item,i) => selection[i] = item.id)
            this.selection = selection
        },
        updateBatch() {
            this.create();
            this.isBatch = true;
        },
		pageChange(page) {
			this.page = page
			this.customerPageQueryList()
		},
		update(item) {
            const { id } = item;
			this.editedIndex = item._index
			this.editedItem = Object.assign({}, item)
            this.showDrawer = true
        },
		create(row) {
            this.editedIndex = -1
            if (row) {
                this.isBatch = false;
                customerGet({id:row.id}).then(res => {
                    if (res.code === '0') {
                        this.editedItem = Object.assign(this.defaultItem, res.data);
                    } else {
                        this.modal(res,'获取患者信息')
                    }
                })
            } else {
			    this.editedItem = Object.assign({}, this.defaultItem)
            }
			this.showDrawer = true
		},
		remove(item, idx) {
			//done this.close();
		},
		async save() {
            if (this.isBatch) {
                const { selection } = this;
                let { templateId,followType,followContent,planTime,planUserId} = this.editedItem;
                if (planTime) {
                    planTime = moment(planTime).format('YYYY-MM-DD HH:mm:ss')
                }
				this.createLoading || (this.createLoading = true)
                const res = await followBatchAdd({
                    customerIds: selection,
                    templateId,followType,followContent,planTime,planUserId,
                })
                this.createLoading = false;
                this.modal(res,'批量随访')
                return 
                
            }
			if (this.editedIndex > -1) {

                // templateId: '',
                // followType: '',
                // customerId: '',
                // followContent: '',
                // planTime: '',
                // planUserId: '',

				const { id,templateId,followType,followContent,planTime,planUserId} = this.editedItem
				this.updateLoading || (this.updateLoading = true)
				const res = await followAdd({ customerId: id,templateId,followType,followContent,planTime,planUserId})
				this.updateLoading = false
                this.modal(res)
			  
			} else {
                let { id,templateId,followType,followContent,planTime,planUserId} = this.editedItem
                if (planTime) {
                    planTime = moment(planTime).format('YYYY-MM-DD HH:mm:ss')
                }
				this.createLoading || (this.createLoading = true)
				const res = await followAdd({ customerId: id,templateId,followType,followContent,planTime,planUserId})
				this.createLoading = false
                this.modal(res)
			}
            this.customerPageQueryList()
		},
		modal(res,title) {
			if (res.code === '0') {
				this.$Modal.success({
					title: title || this.alertTitle,
					content: res.data
                })
                this.close();
			} else {
				this.$Modal.warning({
					title: title || this.alertTitle,
					content: res.errMsg || '提交错误'
                })
			}
		},
		close() {
            this.showDrawer = false
            this.isBatch = false
			setTimeout(() => {
				this.editedItem = Object.assign({}, this.defaultItem)
				this.editedIndex = -1
			}, 10)
		},
        customerPageQueryList() {
            const { customerType,keyWord,tagList,daterange, page, pageSize, loading } = this;
            console.log("daterange1》", daterange)
            const [beginTime, endTime] = daterange;
            console.log("daterange2》", daterange)
            const obj = { beginTime,endTime, customerType,keyWord, tagList,page,pageSize  }
            if (beginTime) {
                obj.beginTime = moment(beginTime).format('YYYY-MM-DD HH:mm:ss')
            }
            if (endTime) {
                obj.endTime = moment(endTime).format('YYYY-MM-DD HH:mm:ss')
            }
            this.loading || (this.loading = true)
			customerPageQueryList(obj)
				.then(res => {
					this.loading = false
					if (res.code === '0') {
                        const { currentPage, isMore, items, pageSize, totalNum, totalPage } = res.data;
                        this.items = items;
                        this.page = currentPage;
                        this.totalNum = totalNum;
						console.log('this.items->', this.items)
					} else {
                        this.$Modal.warning({
							title: '查询列表',
							content: res.errMsg
					    })
                    }
				})
				.catch(err => {
					this.loading = false
				})
		},
	},
	watch: {
		showDrawer(after) {
			after || this.close()
		}
	}
}
</script>
<style scoped>
.ivu-select{
    width: auto;
    min-width: 250px;
}
.time-picker{
    min-width: 250px;
}
.cube{
    max-width: 600px;
}
.label-group {
	display: block;
}
.system-role {
	background-color: #fff;
}
.label {
    min-width: 60px;
    margin-right: 10px;
    display: inline-block;
    vertical-align: middle;
    white-space: nowrap;
    overflow: hidden;
}
</style>